﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections.Generic;

#endregion

namespace ScrumTable.Common.Monitoring
{
    /// <summary>
    /// This class is used to forward import status to an import monitor.
    /// </summary>
    /// <remarks>
    /// An instance of the range import monitor is thread safe.
    /// </remarks>
    public class RangeImportMonitor : IDataImportMonitor
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private readonly IDataImportMonitor _dataImportMonitor;
        private readonly IDictionary<string, byte> _percentageValues = new Dictionary<string, byte>();

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new RangeImportMonitor instance with the specified data.
        /// </summary>
        public RangeImportMonitor(IDataImportMonitor monitor)
        {
            PreCondition.AssertNotNull(monitor, "monitor");

            _dataImportMonitor = monitor;
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Calling this method determins that a new sub import progress has
        /// been started. This means that an additional progress bar should
        /// be displayed.
        /// </summary>
        /// <param name="identifier">Specifies the import identifier (handle). This value
        /// references to the ReportProgress / EndSubProgress methods.</param>
        public void StartSubProgress(string identifier)
        {
            SetPercentageValue(identifier, 0);
            _dataImportMonitor.StartSubProgress(identifier);
        }

        /// <summary>
        /// Reports a progress associated to an identifier (handle).
        /// </summary>
        /// <param name="identifier">Specifies the import identifier (handle). This value
        ///   references to the StartSubProgress / EndSubProgress methods.</param>
        /// <param name="current">Specifies the current state in percent. The maximum is 100.</param>
        public void ReportProgress(string identifier, byte current)
        {
            _dataImportMonitor.ReportProgress(identifier, current);
        }

        /// <summary>
        /// Reports a progress associated to an identifier (handle).
        /// </summary>
        /// <param name="identifier">Specifies the import identifier (handle). This value
        ///   references to the StartSubProgress / EndSubProgress methods.</param>
        /// <param name="current">Specifies the current state.</param>
        /// <param name="max">Specifies the maximum.</param>
        public void ReportProgress(string identifier, int current, int max)
        {
            if (current == 0 || max == 0 || !HasPercentageValue(identifier))
                return;
            
            double quota = Convert.ToDouble(current) / Convert.ToDouble(max);
            double quotaInPercent = Math.Round(quota * 100, MidpointRounding.AwayFromZero);

            if (quotaInPercent > 100)
                quotaInPercent = 100;
            
            byte newPercentageValue = Convert.ToByte(quotaInPercent);
            byte oldPercentageValue = GetPercentageValue(identifier);

            if (newPercentageValue > oldPercentageValue)
            {
                try
                {
                    ReportNewProgress(identifier, current, max, newPercentageValue);
                }
                finally 
                {
                    SetPercentageValue(identifier, newPercentageValue);
                }
            }
        }

        /// <summary>
        /// Reports the end of a progress associated to an identifier (handle).
        /// </summary>
        /// <param name="identifier">Specifies the import identifier (handle). This value
        /// references to the StartSubProgress / ReportProgress methods.</param>
        /// <param name="e">This argument will contain an exception if the progress has been aborted.</param>
        public void EndSubProgress(string identifier, Exception e)
        {
            _dataImportMonitor.EndSubProgress(identifier, e);
            RemovePercentageValue(identifier);
        }

        /// <summary>
        /// Sets and stores the current state into the underlying data structures.
        /// </summary>
        /// <param name="identifier">Specifies the import identifier (handle). This value
        /// references to the StartSubProgress / ReportProgress methods.</param>
        /// <param name="current">Specifies the current state.</param>
        /// <param name="max">Specifies the maximum.</param>
        /// <param name="currentPercent">Specifies the current state in percent. The maximum is 100.</param>
        protected virtual void ReportNewProgress(string identifier, int current, int max, byte currentPercent)
        {
            _dataImportMonitor.ReportProgress(identifier, currentPercent);
        }

        private bool HasPercentageValue(string identifier)
        {
            return _percentageValues.ContainsKey(identifier);
        }

        private byte GetPercentageValue(string identifier)
        {
            return _percentageValues[identifier];
        }

        private void SetPercentageValue(string identifier, byte toSet)
        {
            _percentageValues[identifier] = toSet;
        }

        private void RemovePercentageValue(string identifier)
        {
            _percentageValues.Remove(identifier);
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}